package com.hliushi.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.hliushi.netty.util.ByteBufferUtil.debugRead;

/**
 * @author llhuang10
 * @date 2021/10/17 17:30
 */
@Slf4j
public class BlockServer {

    public static void main(String[] args) throws IOException {
        // 使用 nio 来理解阻塞模式
        // 阻塞在哪里    1是连接的阻塞 2是读取数据的阻塞

        // 0.ByteBuffer
        ByteBuffer buffer = ByteBuffer.allocate(16);
        // 1.创建了服务器
        ServerSocketChannel ssc = ServerSocketChannel.open();

        // 2.绑定监听端口
        ssc.bind(new InetSocketAddress(10010));

        // 3.连接集合
        List<SocketChannel> channels = new ArrayList<>();

        while (true) {
            // 4.accept建立与客户端连接, SocketChannel用户与客户端之间通信
            System.out.println("connecting...");
            SocketChannel sc = ssc.accept();    // 默认阻塞方法, 线程停止运行

            if (sc != null) {
                System.out.println("connected... " + sc);
                channels.add(sc);
            }

            channels.forEach(channel -> {
                // 5.接收客户端发送的数据
                System.out.println("before read... " + channel);
                try {
                    channel.read(buffer);    // 默认堵塞方法
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    System.out.println("after read... " + channel);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
